<template>
  <div>
    <el-drawer
      title="角色菜单"
      :visible.sync="drawerFlag"
      size="30%"
      append-to-body
      @close="closeDrawer"
    >
      <div style="padding: 20px;">
        <el-button size="small" type="primary" @click="saveMenu" :loading="loading.add">保存</el-button>
        <el-button size="small" @click="closeDrawer">关闭</el-button>
        <el-tooltip content="刷新" placement="right">
          <el-button
            size="small"
            icon="el-icon-refresh"
            type="success"
            circle
            @click="initData(role)"
          ></el-button>
        </el-tooltip>
        <el-divider />
        <div style="height: 100vh; padding-bottom: 200px;">
          <el-scrollbar>
            <el-tree
              :data="menuData"
              :props="defaultProps"
              node-key="id"
              show-checkbox
              ref="menuTree"
            ></el-tree>
          </el-scrollbar>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { doGet, doPostJson } from '@/utils/utils'
import * as ResponseStatus from '@/utils/response-status'
export default {
  name: 'SysMenuAssignDrawer',
  props: {},
  data() {
    return {
      role: {},
      drawerFlag: false,
      roleMenuData: [],
      userMenuData: [],
      menuData: [],
      checkMenuIds: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      loading: {
        add: false,
      },
    }
  },
  mounted() {},
  methods: {
    /**
     * 初始化数据，请求后端数据
     * @param role 角色
     */
    initData(role) {
      this.drawerFlag = true
      this.role = role
      // 获取当前指定角色的菜单
      doGet('/sys-menu/admin/all-menu/' + this.role.id, {})
        .then((res) => {
          this.roleMenuData = res.data
          // 获取当前登录用户的所有菜单
          doGet('/sys-menu/admin/all-menu', {})
            .then((res) => {
              this.userMenuData = res.data
              this.initMenuData()
            })
            .catch((err) => {})
        })
        .catch((err) => {})
    },
    /**
     * 初始化菜单数据
     */
    initMenuData() {
      this.menuData = []
      this.checkMenuIds = []
      // 获取到所有一级菜单
      let oneLevelMenuArr = this.userMenuData.filter((item) => {
        return item.menuLevel === 1
      })
      // 获取到所有二级菜单
      let twoLevelMenuArr = this.userMenuData.filter((item) => {
        return item.menuLevel === 2
      })
      // 获取到所有三级菜单
      let threeLevelMenuArr = this.userMenuData.filter((item) => {
        return item.menuLevel === 3
      })
      // 循环一级菜单
      oneLevelMenuArr.forEach((oneLevelMenu) => {
        let oneMenuId = oneLevelMenu.id
        let oneLevelChildren = []
        // 循环二级菜单
        twoLevelMenuArr.forEach((twoLevelMenu) => {
          if (oneMenuId === twoLevelMenu.parentId) {
            let twoMenuId = twoLevelMenu.id
            let twoLevelChildren = []
            // 循环三级菜单
            threeLevelMenuArr.forEach((threeLevelMenu) => {
              if (twoMenuId === threeLevelMenu.parentId) {
                const threeLevelMenuData = this.encapsulationData(
                  threeLevelMenu,
                  false
                )
                twoLevelChildren.push(threeLevelMenuData)
              }
            })
            const twoLevelMenuData = this.encapsulationData(twoLevelMenu, twoLevelChildren.length > 0)
            twoLevelMenuData.children = twoLevelChildren
            oneLevelChildren.push(twoLevelMenuData)
          }
        })
        const oneLevelMenuData = this.encapsulationData(oneLevelMenu, oneLevelChildren.length > 0)
        oneLevelMenuData.children = oneLevelChildren
        this.menuData.push(oneLevelMenuData)
      })

      setTimeout(() => {
        this.$refs.menuTree.setCheckedKeys(this.checkMenuIds)
      }, 10)
    },
    /**
     * 根据菜单数据封装成需要的菜单数据
     * @param {}} menu
     */
    encapsulationData(menu, hasChildren) {
      let menuData = {
        id: menu.id,
        label: menu.metaTitle,
        name: menu.name,
      }
      if ((menu.menuLevel === 3) || (menu.menuLevel === 2 && !hasChildren) || (menu.menuLevel === 1 && !hasChildren)) {
        // 只有三级菜单或者没有下级的二级菜单或者没有下级的一级菜单需要被设置为选中
        this.roleMenuData.forEach((menuItem) => {
          if (menuItem.id === menu.id) {
            this.checkMenuIds.push(menuItem.id)
          }
        })
      }
      return menuData
    },
    // 关闭权限配置
    closeDrawer() {
      this.drawerFlag = false
      this.menuData = []
    },
    /**
     * 保存权限
     */
    saveMenu() {
      // 包含半选结点
      let checkedNodes = this.$refs.menuTree.getCheckedNodes(false, true)
      let sysMenus = checkedNodes
      let params = []
      sysMenus.forEach((sysMenu) => {
        // 对所有选中和半选中的数据进行遍历，去除第一个
        params.push({
          roleId: this.role.id,
          roleTitle: this.role.title,
          roleIsActive: this.role.isActive,
          sysMenuId: sysMenu.id,
          sysMenuName: sysMenu.name,
          sysMenuMetaTitle: sysMenu.label,
          sysMenuIsActive: 1,
        })
      })
      this.loading.add = true
      doPostJson(
        '/role-menu/admin/remove-batch-save/' + this.role.id + '/' + this.role.title,
        params,
        {}
      )
        .then((res) => {
          this.$message.success('保存角色菜单成功')
          this.drawerFlag = false
          this.loading.add = false
        })
        .catch((err) => {
          this.loading.add = false
        })
    },
  },
}
</script>
